import cbor from "cbor-js"

export function formatCurrency(
    value: number,
    opts?: {
        currency?: string
        minimumFractionDigits?: number
        maximumFractionDigits?: number
    },
) {
    return Intl.NumberFormat("en-US", {
        style: "currency",
        currency: opts?.currency || "PHP",
        minimumFractionDigits: opts?.minimumFractionDigits ?? 2,
        maximumFractionDigits: opts?.maximumFractionDigits ?? 2,
    }).format(value)
}

export const PayloadFormatter = {
    encode: (payload: Record<string, unknown>): string => {
        // 使用 Uint8Array 而不是 Buffer
        const encoded = cbor.encode(payload)
        // 將二進制數據轉換為正確的 base64 字符串
        return btoa(
            Array.from(new Uint8Array(encoded))
                .map((b) => String.fromCharCode(b))
                .join(""),
        )
    },
    decode: (base64: string): Record<string, unknown> => {
        try {
            // 從 base64 轉換為二進制數據
            const binary = atob(base64)
            const bytes = new Uint8Array(binary.length)
            for (let i = 0; i < binary.length; i++) {
                bytes[i] = binary.charCodeAt(i)
            }
            // 使用 cbor 解碼二進制數據
            return cbor.decode(bytes.buffer)
        } catch (error) {
            console.error("PayloadFormatter.decode failed:", error)
            return {}
        }
    },
    jsonParse: (json?: string): Record<string, unknown> => {
        try {
            return JSON.parse(json || "{}")
        } catch (error) {
            console.error("PayloadFormatter.jsonParse failed:", error)
            return {}
        }
    },
    jsonStringify: (payload: Record<string, unknown>): string => {
        try {
            return JSON.stringify(payload)
        } catch (error) {
            console.error("PayloadFormatter.jsonStringify failed:", error)
            return "{}"
        }
    },
}
